//
//  RunVC.m
//  timelyRain
//
//  Created by Jiafei Wei on 16/8/24.
//  Copyright © 2016年 Jiafei Wei. All rights reserved.
//

#import "RunVC.h"
#import "RunFooter.h"
#import "RunHeader.h"
#import "RunRecordVC.h"
#import "HttpTool.h"
#import "PageData.h"
#import "MJRefresh.h"
#import "RunSucessInfo.h"
#import "RunData.h"
#import "RunRecordInfo.h"
#import "RunCell.h"
#import "MBTUiColor.h"
#import "RunRecordGroupInfo.h"
#import "DataTool.h"
#import "SportLocusVC.h"
#import "TestVCViewController.h"
@interface RunVC ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>{
    RunHeader *h;
    NSMutableArray *sportData;
    PageData *page;
}
@property (weak, nonatomic) IBOutlet UITableView *table;
@property (weak, nonatomic) IBOutlet UILabel *sportDistance;
@property (weak, nonatomic) IBOutlet UILabel *sportTime;
@property (weak, nonatomic) IBOutlet UILabel *sportMin;

@end

@implementation RunVC

- (void)viewDidLoad {
    [super viewDidLoad];
    sportData =[NSMutableArray array];
    page =[[PageData alloc]init];
    _table.delegate =self;
    _table.dataSource=self;
    [self goToRunRecord];//执行跳转
    [self RefreshSport];
}
-(void)RefreshSport{
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    __unsafe_unretained __typeof(self) weakSelf = self;
    _table.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{//下拉刷新
        [weakSelf updateSports];
    }];
    [_table.mj_header beginRefreshing];
    
    _table.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadMoreSports];
    }];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RunCell *cell =  [RunCell setRunCellWithTableView:tableView];
    RunRecordInfo *info = sportData[indexPath.row];
    cell.info =info;
    return cell;
}
//为什么一定要在这里显示啊？
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //在这里添加点击事件
    return h ;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return sportData.count;
}
//-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
//    return [RunFooter footerView];
//}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//        SportLocusVC *locus =[[SportLocusVC alloc]init];
//        locus.info =sportData[indexPath.row];
//        [self.navigationController pushViewController:locus animated:YES];
//
    TestVCViewController *locus =[[TestVCViewController alloc]init];
    [self.navigationController pushViewController:locus animated:YES];
}
-(void)goToRunRecord{
    h = [RunHeader headerView];
    h.backgroundColor =[UIColor colorwithHexString:@"#F4F3F8"];
    h.userInteractionEnabled = YES;
    UITapGestureRecognizer *addTapGest = [[UITapGestureRecognizer alloc] init];
    addTapGest.numberOfTapsRequired = 1;
    addTapGest.delegate = self;
    [h addGestureRecognizer:addTapGest];
    [addTapGest addTarget:self action:@selector(addTapView:)];
}
- (void)addTapView:(UITapGestureRecognizer *)addTapGest{
    RunRecordVC *record =[[RunRecordVC alloc]initWithNibName:@"RunRecordVC"bundle:nil];
    record.grounp =[self calculateSportGrounp:sportData];
    [self.navigationController pushViewController:record animated:YES];
}
//每次加载10条
-(void)updateSports{//请求数据的方法
    page.page =1;
    NSDictionary *params = @{@"user_id":@"phone13480151236",@"page":@1,@"pageSize":@10};;
    [HttpTool GET:@"http://www.aiaiaini.com/demo/web/index.php?r=api/sport/get-sports" WithHeader:NO parameters:params success:^(id responseObject) {
        RunSucessInfo *info =[RunSucessInfo mj_objectWithKeyValues:responseObject];
        if (info.status){
            RunData *data = [RunData mj_objectWithKeyValues:info.data];
            NSArray *dataArr =data.sports;
            page.page=data.pageData.page;//重新赋值
            if (sportData.count!=0) {
                [sportData removeAllObjects];
            }
            [sportData addObjectsFromArray:dataArr];
            NSString *count = [NSString stringWithFormat:@"%lu",(unsigned long)sportData.count];
            h.rumNumber.text=count;
            [_table reloadData];
            [self calculateSport:sportData];
        }else{
            //数据错提示
        }
        [_table.mj_header endRefreshing];
    } failure:^(NSError *error){
        [_table.mj_header endRefreshing];
         NSLog(@"%@",error);
    }];
}
-(void)loadMoreSports{
    //上拉加载更多的数据
    page.page =page.page+1;
    NSNumber *pageNumber = [NSNumber numberWithInt:page.page];//
    NSDictionary *params = @{@"user_id":@"phone13480151236",@"page":pageNumber,@"pageSize":@10};
    [HttpTool GET:@"http://www.aiaiaini.com/demo/web/index.php?r=api/sport/get-sports" WithHeader:NO parameters:params success:^(id responseObject) {
        RunSucessInfo *info =[RunSucessInfo mj_objectWithKeyValues:responseObject];
        if (info.status) {
            RunData *data = [RunData mj_objectWithKeyValues:info.data];
            NSArray *dataArr =data.sports;
            if (dataArr.count==0) {
                //提示数据没有更多了
            }else{
                [sportData addObjectsFromArray:dataArr];
                NSString *count = [NSString stringWithFormat:@"%lu",(unsigned long)sportData.count];
                h.rumNumber.text=count;
                [_table reloadData];
                [self calculateSport:sportData];
            }
        }else{
            //数据错提示
        }
        [_table.mj_footer endRefreshing];//刷新成功
    } failure:^(NSError *error){
        [_table.mj_footer endRefreshing];//在这里提示刷新失败
    }];
}
//进行分组
-(void)calculateSport:(NSMutableArray *)data{
    float d =0.0f;
    float t =0;
    for (RunRecordInfo *r in data) {
        d =d +[r.distance floatValue];
        t = t +[r.time floatValue];
    }
    //保留一位小数
    NSString *dis =[NSString stringWithFormat:@"%.1f",d/1000];//总距离
    NSString *time =[NSString stringWithFormat:@"%.1f",t/3600];//总时间
    _sportTime.text=time;
    _sportDistance.text=dis;
    _sportMin.text=[NSString stringWithFormat:@"%.2f",(t/3600)/(d/1000)];
}
//写一个计算分组的方法
-(NSMutableArray *)calculateSportGrounp:(NSMutableArray *)data{
    //按月份分的组
    NSMutableArray *grounp =[NSMutableArray array];
    for (int i=1;i<13;i++) {//创建对象
        RunRecordGroupInfo *h =[[RunRecordGroupInfo alloc]init];
        h.runRecordGroup =[NSMutableArray array];
        [grounp addObject:h];//对应月份
    }
    for (RunRecordInfo *r in data){
        NSDateComponents *com =[DataTool getNSDateComponents:[r.create_at longLongValue]];
        NSInteger month = [com month];//月份
        RunRecordGroupInfo *rh =grounp[month];
        rh.month =[[NSString stringWithFormat:@"%i",(int)month] stringByAppendingString:@"月"];
        rh.distance +=[r.distance floatValue];
        rh.time +=[r.time floatValue];//计算总数
        rh.expend=NO;
        [rh.runRecordGroup addObject:r];
    }
     NSMutableArray *grounp1 =[NSMutableArray array];
    for (RunRecordGroupInfo *g in grounp){
        if (g.runRecordGroup.count==0){
            [grounp1 addObject:g];
        }
    }
    [grounp removeObjectsInArray:grounp1];//过滤出没有数据的集合
    return grounp;
}
@end
